package com.smartcampusbackend.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.smartcampusbackend.model.Resource;
import com.smartcampusbackend.model.ResourceBooking;
import com.smartcampusbackend.service.ResourceService;
import com.smartcampusbackend.service.TokenService;
import com.smartcampusbackend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.security.Principal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.stream.Collectors;
import java.io.File;
import java.net.URLEncoder;
import java.nio.file.Files;

@RestController
@RequestMapping("/api/resource")
@CrossOrigin(origins = "*")
public class ResourceController {

    @Autowired
    private ResourceService resourceService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private UserService userService;

    // ==================== 资源管理接口 ====================

    // 工具方法：通过token获取用户
    private com.smartcampusbackend.model.User getUserByToken(String token) {
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        String username = tokenService.getUsernameByToken(token);
        if (username != null) {
            return userService.getByUsername(username);
        }
        return null;
    }

    /**
     * 上传资源
     */
    @PostMapping("/upload")
    public Map<String, Object> uploadResource(
            @RequestParam("title") String title,
            @RequestParam("description") String description,
            @RequestParam("category") String category,
            @RequestParam("type") String type,
            @RequestParam(value = "tags", required = false) String tags,
            @RequestParam(value = "equipmentInfo", required = false) String equipmentInfo,
            @RequestParam(value = "file", required = false) MultipartFile file,
            @RequestHeader("Authorization") String token,
            HttpServletRequest request) {

        try {
            com.smartcampusbackend.model.User user = getUserByToken(token);
            if (user == null) {
                Map<String, Object> result = new HashMap<>();
                result.put("code", 401);
                result.put("message", "无效的token");
                return result;
            }

            // 检查用户是否有上传权限（教师或管理员）
            if (!"TEACHER".equals(user.getRole()) && !"ADMIN".equals(user.getRole())) {
                Map<String, Object> result = new HashMap<>();
                result.put("code", 403);
                result.put("message", "权限不足，只有教师和管理员可以上传资源");
                return result;
            }

            // 构建资源对象
            Resource resource = new Resource();
            resource.setTitle(title);
            resource.setDescription(description);
            resource.setCategory(category);
            resource.setType(type);
            resource.setTags(tags);
            resource.setEquipmentInfo(equipmentInfo);
            resource.setUploaderId(String.valueOf(user.getId()));
            resource.setUploaderName(user.getRealName() != null ? user.getRealName() : user.getUsername());

            return resourceService.uploadResource(resource, file);

        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("message", "上传异常：" + e.getMessage());
            return result;
        }
    }

    /**
     * 更新资源
     */
    @PutMapping("/update")
    public Map<String, Object> updateResource(
            @RequestParam("id") String id,
            @RequestParam("title") String title,
            @RequestParam("description") String description,
            @RequestParam("category") String category,
            @RequestParam("type") String type,
            @RequestParam(value = "tags", required = false) String tags,
            @RequestParam(value = "equipmentInfo", required = false) String equipmentInfo,
            @RequestParam(value = "file", required = false) MultipartFile file,
            @RequestHeader("Authorization") String token) {

        try {
            com.smartcampusbackend.model.User user = getUserByToken(token);
            if (user == null) {
                Map<String, Object> result = new HashMap<>();
                result.put("code", 401);
                result.put("message", "无效的token");
                return result;
            }

            // 构建资源对象
            Resource resource = new Resource();
            resource.setId(id);
            resource.setTitle(title);
            resource.setDescription(description);
            resource.setCategory(category);
            resource.setType(type);
            resource.setTags(tags);
            resource.setEquipmentInfo(equipmentInfo);

            return resourceService.updateResource(resource, file);

        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("message", "更新异常：" + e.getMessage());
            return result;
        }
    }

    /**
     * 删除资源
     */
    @DeleteMapping("/{id}")
    public Map<String, Object> deleteResource(
            @PathVariable String id,
            @RequestHeader("Authorization") String token) {

        try {
            com.smartcampusbackend.model.User user = getUserByToken(token);
            if (user == null) {
                Map<String, Object> result = new HashMap<>();
                result.put("code", 401);
                result.put("message", "无效的token");
                return result;
            }

            return resourceService.deleteResource(id, String.valueOf(user.getId()), user.getRole());

        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("message", "删除异常：" + e.getMessage());
            return result;
        }
    }

    /**
     * 获取资源详情
     */
    @GetMapping("/{id}")
    public Map<String, Object> getResourceById(
            @PathVariable String id,
            @RequestHeader(value = "Authorization", required = false) String token) {

        try {
            // 如果token为空，仍然返回资源详情（公开访问）
            if (token == null || token.isEmpty() || !token.startsWith("Bearer ")) {
                return resourceService.getResourceById(id);
            }

            // 验证token
            String tokenValue = token.substring(7);
            String username = tokenService.getUsernameByToken(tokenValue);

            // 即使token无效，也返回资源详情
            return resourceService.getResourceById(id);
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("message", "获取资源详情异常：" + e.getMessage());
            return result;
        }
    }

    /**
     * 获取资源列表
     */
    @GetMapping("/list")
    public Map<String, Object> getResourceList(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) String keyword,
            @RequestHeader(value = "Authorization", required = false) String token) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("current", current);
            params.put("size", size);
            params.put("category", category);
            params.put("type", type);
            params.put("keyword", keyword);
            IPage<Resource> page = resourceService.getResourceList(params);
            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("message", "获取成功");
            result.put("data", page);
            return result;
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("message", "获取资源列表异常：" + e.getMessage());
            return result;
        }
    }

    /**
     * 获取所有资源（管理用）
     */
    @GetMapping("/all")
    public Map<String, Object> getAllResources(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String keyword,
            @RequestHeader("Authorization") String token) {
        try {
            com.smartcampusbackend.model.User user = getUserByToken(token);
            if (user == null) {
                Map<String, Object> result = new HashMap<>();
                result.put("code", 401);
                result.put("message", "无效的token");
                return result;
            }
            if (!"ADMIN".equals(user.getRole())) {
                Map<String, Object> result = new HashMap<>();
                result.put("code", 403);
                result.put("message", "权限不足");
                return result;
            }

            Map<String, Object> params = new HashMap<>();
            params.put("current", current);
            params.put("size", size);
            params.put("category", category);
            params.put("type", type);
            params.put("status", status);
            params.put("keyword", keyword);

            IPage<Resource> page = resourceService.getAllResources(params);

            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("message", "获取成功");
            result.put("data", page);

            return result;
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("message", "获取资源列表异常：" + e.getMessage());
            return result;
        }
    }

    /**
     * 获取我的资源
     */
    @GetMapping("/my")
    public Map<String, Object> getMyResources(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String status,
            @RequestHeader("Authorization") String token) {

        try {
            com.smartcampusbackend.model.User user = getUserByToken(token);
            if (user == null) {
                Map<String, Object> result = new HashMap<>();
                result.put("code", 401);
                result.put("message", "无效的token");
                return result;
            }

            Map<String, Object> params = new HashMap<>();
            params.put("current", current);
            params.put("size", size);
            params.put("status", status);

            IPage<Resource> page = resourceService.getMyResources(String.valueOf(user.getId()), params);

            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("message", "获取成功");
            result.put("data", page);

            return result;

        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("message", "获取异常：" + e.getMessage());
            return result;
        }
    }

    // ==================== 审核管理接口 ====================

    /**
     * 审核资源
     */
    @PostMapping("/review/{id}")
    public Map<String, Object> reviewResource(
            @PathVariable String id,
            @RequestBody Map<String, Object> reviewData,
            @RequestHeader("Authorization") String token) {

        try {
            com.smartcampusbackend.model.User user = getUserByToken(token);
            if (user == null) {
                Map<String, Object> result = new HashMap<>();
                result.put("code", 401);
                result.put("message", "无效的token");
                return result;
            }

            String status = (String) reviewData.get("status");
            String comment = (String) reviewData.get("comment");

            return resourceService.reviewResource(id, status, comment, String.valueOf(user.getId()), user.getRealName() != null ? user.getRealName() : user.getUsername());

        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("message", "审核异常：" + e.getMessage());
            return result;
        }
    }

    /**
     * 获取待审核资源
     */
    @GetMapping("/pending")
    public Map<String, Object> getPendingResources(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestHeader("Authorization") String token) {

        try {
            // 验证token
            String tokenValue = token.substring(7);
            String username = tokenService.getUsernameByToken(tokenValue);
            if (username == null) {
                Map<String, Object> result = new HashMap<>();
                result.put("code", 401);
                result.put("message", "无效的token");
                return result;
            }

            Map<String, Object> params = new HashMap<>();
            params.put("current", current);
            params.put("size", size);

            IPage<Resource> page = resourceService.getPendingResources(params);

            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("message", "获取成功");
            result.put("data", page);

            return result;
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("message", "获取待审核资源异常：" + e.getMessage());
            return result;
        }
    }

    // ==================== 下载和统计接口 ====================

    /**
     * 下载资源
     */
    @PostMapping("/download/{id}")
    public Map<String, Object> downloadResource(
            @PathVariable String id,
            @RequestHeader("Authorization") String token,
            HttpServletRequest request) {

        try {
            com.smartcampusbackend.model.User user = getUserByToken(token);
            if (user == null) {
                Map<String, Object> result = new HashMap<>();
                result.put("code", 401);
                result.put("message", "无效的token");
                return result;
            }

            String ipAddress = request.getRemoteAddr();
            String userAgent = request.getHeader("User-Agent");

            return resourceService.downloadResource(id, String.valueOf(user.getId()), user.getRealName() != null ? user.getRealName() : user.getUsername(), ipAddress, userAgent);

        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("message", "下载异常：" + e.getMessage());
            return result;
        }
    }

    /**
     * 获取下载统计
     */
    @GetMapping("/statistics/{id}")
    public Map<String, Object> getDownloadStatistics(
            @PathVariable String id,
            @RequestHeader("Authorization") String token) {

        try {
            com.smartcampusbackend.model.User user = getUserByToken(token);
            if (user == null) {
                Map<String, Object> result = new HashMap<>();
                result.put("code", 401);
                result.put("message", "无效的token");
                return result;
            }

            return resourceService.getDownloadStatistics(id);
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("message", "获取下载统计异常：" + e.getMessage());
            return result;
        }
    }

    // ==================== 搜索和分类接口 ====================

    /**
     * 搜索资源
     */
    @GetMapping("/search")
    public Map<String, Object> searchResources(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String type,
            @RequestHeader(value = "Authorization", required = false) String token) {

        try {
            // 如果token为空，仍然返回搜索结果（公开访问）
            if (token == null || token.isEmpty() || !token.startsWith("Bearer ")) {
                Map<String, Object> params = new HashMap<>();
                params.put("current", current);
                params.put("size", size);
                params.put("keyword", keyword);
                params.put("category", category);
                params.put("type", type);

                IPage<Resource> page = resourceService.searchResources(params);

                Map<String, Object> result = new HashMap<>();
                result.put("code", 200);
                result.put("message", "搜索成功");
                result.put("data", page);

                return result;
            }

            // 验证token
            String tokenValue = token.substring(7);
            String username = tokenService.getUsernameByToken(tokenValue);

            // 即使token无效，也返回搜索结果
            Map<String, Object> params = new HashMap<>();
            params.put("current", current);
            params.put("size", size);
            params.put("keyword", keyword);
            params.put("category", category);
            params.put("type", type);

            IPage<Resource> page = resourceService.searchResources(params);

            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("message", "搜索成功");
            result.put("data", page);

            return result;
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("message", "搜索资源异常：" + e.getMessage());
            return result;
        }
    }

    /**
     * 获取资源分类
     */
    @GetMapping("/categories")
    public Map<String, Object> getResourceCategories(
            @RequestHeader(value = "Authorization", required = false) String token) {

        try {
            // 如果token为空，仍然返回资源分类（公开访问）
            if (token == null || token.isEmpty() || !token.startsWith("Bearer ")) {
                return resourceService.getResourceCategories();
            }

            // 验证token
            String tokenValue = token.substring(7);
            String username = tokenService.getUsernameByToken(tokenValue);

            // 即使token无效，也返回资源分类
            return resourceService.getResourceCategories();
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("message", "获取资源分类异常：" + e.getMessage());
            return result;
        }

    }

    // ==================== 设备预约接口 ====================

    // 设备预约：创建预约
    @PostMapping("/booking")
    public Map<String, Object> createBooking(@RequestBody ResourceBooking booking, @RequestHeader("Authorization") String token) {
        com.smartcampusbackend.model.User user = getUserByToken(token);
        if (user == null) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 401);
            result.put("message", "无效的token");
            return result;
        }
        booking.setUserId(user.getId());
        booking.setUserName(user.getRealName() != null ? user.getRealName() : user.getUsername());
        // 自动填充resourceTitle
        com.smartcampusbackend.model.Resource resource = resourceService.getResourceByIdObj(String.valueOf(booking.getResourceId()));
        if (resource != null) {
            booking.setResourceTitle(resource.getTitle());
        } else {
            booking.setResourceTitle("");
        }
        booking.setCreateTime(new Date());
        int result = resourceService.createBooking(booking);
        Map<String, Object> resp = new HashMap<>();
        if (result > 0) {
            resp.put("code", 200);
            resp.put("message", "预约成功");
        } else {
            resp.put("code", 500);
            resp.put("message", "预约失败");
        }
        return resp;
    }

    // 设备预约：获取我的预约
    @GetMapping("/booking/my")
    public Map<String, Object> getMyBookings(@RequestHeader("Authorization") String token) {
        com.smartcampusbackend.model.User user = getUserByToken(token);
        if (user == null) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 401);
            result.put("message", "无效的token");
            return result;
        }
        List<ResourceBooking> list = resourceService.getBookingsByUser(user.getId());
        Map<String, Object> resp = new HashMap<>();
        resp.put("code", 200);
        resp.put("data", list);
        return resp;
    }

    // 设备预约：获取所有预约（管理员）
    @GetMapping("/booking/pending")
    public Map<String, Object> getAllBookings(
            @RequestParam(required = false) String status, 
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestHeader("Authorization") String token) {
        com.smartcampusbackend.model.User user = getUserByToken(token);
        if (user == null || !"ADMIN".equals(user.getRole())) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 403);
            result.put("message", "权限不足");
            return result;
        }
        
        try {
            List<ResourceBooking> list;
            if (status != null && !status.isEmpty()) {
                list = resourceService.getBookingsByStatus(status);
            } else {
                list = resourceService.getAllBookings();
            }
            
            // 如果有关键词，进行过滤
            if (keyword != null && !keyword.trim().isEmpty()) {
                String lowerKeyword = keyword.toLowerCase();
                list = list.stream()
                    .filter(b -> (b.getResourceTitle() != null && b.getResourceTitle().toLowerCase().contains(lowerKeyword)) ||
                                (b.getUserName() != null && b.getUserName().toLowerCase().contains(lowerKeyword)))
                    .collect(Collectors.toList());
            }
            
            // 手动分页
            int total = list.size();
            int start = (current - 1) * size;
            int end = Math.min(start + size, total);
            
            List<ResourceBooking> pagedList = list.subList(start, end);
            
            Map<String, Object> resp = new HashMap<>();
            resp.put("code", 200);
            resp.put("data", pagedList);
            resp.put("total", total);
            resp.put("current", current);
            resp.put("size", size);
            return resp;
            
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("message", "获取预约列表失败：" + e.getMessage());
            return result;
        }
    }

    // 设备预约：审批预约
    @PostMapping("/booking/approve/{id}")
    public Map<String, Object> approveBooking(@PathVariable Integer id, @RequestHeader("Authorization") String token) {
        com.smartcampusbackend.model.User user = getUserByToken(token);
        if (user == null) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 401);
            result.put("message", "无效的token");
            return result;
        }
        ResourceBooking booking = new ResourceBooking();
        booking.setId(id);
        booking.setStatus("APPROVED");
        booking.setApproverId(user.getId());
        booking.setApproverName(user.getRealName() != null ? user.getRealName() : user.getUsername());
        booking.setApproveTime(new Date());
        int result = resourceService.updateBooking(booking);
        Map<String, Object> resp = new HashMap<>();
        if (result > 0) {
            resp.put("code", 200);
            resp.put("message", "审批成功");
        } else {
            resp.put("code", 500);
            resp.put("message", "审批失败");
        }
        return resp;
    }

    // 设备预约：拒绝预约
    @PostMapping("/booking/reject/{id}")
    public Map<String, Object> rejectBooking(@PathVariable Integer id, @RequestBody(required = false) Map<String, Object> param, @RequestHeader("Authorization") String token) {
        com.smartcampusbackend.model.User user = getUserByToken(token);
        if (user == null) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 401);
            result.put("message", "无效的token");
            return result;
        }
        ResourceBooking booking = new ResourceBooking();
        booking.setId(id);
        booking.setStatus("REJECTED");
        booking.setApproverId(user.getId());
        booking.setApproverName(user.getRealName() != null ? user.getRealName() : user.getUsername());
        booking.setApproveTime(new Date());
        if (param != null && param.get("comment") != null) {
            booking.setApproveComment(param.get("comment").toString());
        }
        int result = resourceService.updateBooking(booking);
        Map<String, Object> resp = new HashMap<>();
        if (result > 0) {
            resp.put("code", 200);
            resp.put("message", "拒绝成功");
        } else {
            resp.put("code", 500);
            resp.put("message", "拒绝失败");
        }
        return resp;
    }

    // 设备预约：取消预约
    @PostMapping("/booking/cancel/{id}")
    public Map<String, Object> cancelBooking(@PathVariable Integer id, @RequestHeader("Authorization") String token) {
        com.smartcampusbackend.model.User user = getUserByToken(token);
        if (user == null) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 401);
            result.put("message", "无效的token");
            return result;
        }
        int result = resourceService.cancelBooking(id, user.getId());
        Map<String, Object> resp = new HashMap<>();
        if (result > 0) {
            resp.put("code", 200);
            resp.put("message", "取消成功");
        } else {
            resp.put("code", 500);
            resp.put("message", "取消失败");
        }
        return resp;
    }

    // 设备预约：检测预约冲突
    @GetMapping("/booking/check-conflict")
    public Map<String, Object> checkBookingConflict(
            @RequestParam String resourceId,
            @RequestParam String bookingDate,
            @RequestParam String startTime,
            @RequestParam String endTime,
            @RequestHeader("Authorization") String token) {
        com.smartcampusbackend.model.User user = getUserByToken(token);
        Map<String, Object> result = new HashMap<>();
        if (user == null) {
            result.put("code", 401);
            result.put("message", "无效的token");
            return result;
        }
        
        try {
            // 将日期字符串转换为Date对象
            java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
            Date bookingDateObj = sdf.parse(bookingDate.substring(0, 10));
            
            // 查询该设备当天所有已通过和待审批的预约
            List<ResourceBooking> bookings = resourceService.getBookingsByResourceIdAndDate(resourceId, bookingDateObj);
            
            // 过滤掉当前用户的预约
            bookings = bookings.stream()
                .filter(b -> !b.getUserId().equals(user.getId()))
                .collect(Collectors.toList());
            
            // 检查时间冲突
            boolean conflict = bookings.stream().anyMatch(b -> {
                return isTimeConflict(startTime, endTime, b.getStartTime(), b.getEndTime());
            });
            
            result.put("code", 200);
            result.put("conflict", conflict);
            if (conflict) {
                result.put("message", "该时间段已被预约，请选择其他时间");
            } else {
                result.put("message", "时间可用");
            }
            
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "检查冲突失败：" + e.getMessage());
        }
        
        return result;
    }
    
    // 辅助方法：检查时间冲突
    private boolean isTimeConflict(String start1, String end1, String start2, String end2) {
        // 将时间字符串转换为分钟数进行比较
        int start1Minutes = timeToMinutes(start1);
        int end1Minutes = timeToMinutes(end1);
        int start2Minutes = timeToMinutes(start2);
        int end2Minutes = timeToMinutes(end2);
        
        // 检查是否有重叠：两个时间段不重叠的条件是 end1 <= start2 或 end2 <= start1
        return !(end1Minutes <= start2Minutes || end2Minutes <= start1Minutes);
    }
    
    // 辅助方法：将时间字符串转换为分钟数
    private int timeToMinutes(String time) {
        if (time == null || time.isEmpty()) {
            return 0;
        }
        String[] parts = time.split(":");
        if (parts.length == 2) {
            int hours = Integer.parseInt(parts[0]);
            int minutes = Integer.parseInt(parts[1]);
            return hours * 60 + minutes;
        }
        return 0;
    }

    /**
     * 文件下载接口，支持a标签直接下载
     */
    @GetMapping("/file-download/{id}")
    public void fileDownload(@PathVariable String id, HttpServletResponse response) {
        try {
            Resource resource = resourceService.getResourceByIdObj(id);
            if (resource == null || resource.getFileUrl() == null) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
            File file = new File(resource.getFileUrl());
            if (!file.exists()) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
            String fileName = resource.getFileName() != null ? resource.getFileName() : file.getName();
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
            Files.copy(file.toPath(), response.getOutputStream());
            response.flushBuffer();
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

}

